package com.lty.protocol.tcp;

import com.lty.protocol.tcp.handler.DecoderHandler;
import com.lty.protocol.tcp.handler.EchoHandler;
import com.lty.protocol.tcp.handler.EncoderHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LoggingHandler;

import javax.annotation.PostConstruct;

/**
 * @ClassName TcpClient
 * @Description tcp客户端启动类
 * @Author Administrator
 * @DATE 2023/12/12 14:50
 * @Version 1.0
 */
public class TcpClient {

    public static final String ip = "127.0.0.1";
    public static final int port = 17777;

    @PostConstruct
    public void init() throws InterruptedException {
        NioEventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group);
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
            bootstrap.handler(new ChannelInitializer() {
                @Override
                protected void initChannel(Channel ch) throws Exception {
                    ch.pipeline().addLast("logging", new LoggingHandler("DEBUG"));
                    ch.pipeline().addLast(new EncoderHandler());
                    ch.pipeline().addLast(new DecoderHandler());
                    ch.pipeline().addLast(new EchoHandler());
                }
            });
            bootstrap.remoteAddress(ip, port);
            ChannelFuture future = bootstrap.connect().sync();

            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully().sync();
        }
    }

    public static void main(String[] args) {
        try {
            new TcpClient().init();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
